package io.renren.modules.alarmonline.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.modules.alarmhistory.entity.AreaalarmHistoryEntity;
import io.renren.modules.alarmonline.service.WebSocketService;
import io.renren.modules.area.dao.AreaDao;
import io.renren.modules.area.entity.AreaEntity;
import io.renren.modules.labonin.dao.LableonlineinfoDao;
import io.renren.modules.posinfo.entity.Utype1Entity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.alarmonline.dao.AreaalarmOnlineDao;
import io.renren.modules.alarmonline.entity.AreaalarmOnlineEntity;
import io.renren.modules.alarmonline.service.AreaalarmOnlineService;

@Slf4j
@Service("areaalarmOnlineService")
public class AreaalarmOnlineServiceImpl extends ServiceImpl<AreaalarmOnlineDao, AreaalarmOnlineEntity> implements AreaalarmOnlineService {

    @Autowired
    AreaalarmOnlineDao areaalarmOnlineDao;


    @Autowired
    AreaDao areaDao;

    @Autowired
    LableonlineinfoDao lableonlineinfoDao;


    @Autowired
    WebSocketService webSocketService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AreaalarmOnlineEntity> page = this.page(
                new Query<AreaalarmOnlineEntity>().getPage(params),
                new QueryWrapper<AreaalarmOnlineEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public int insertItem(AreaalarmOnlineEntity areaalarmOnlineEntity) {
        webSocketService.sendMessage(JSONObject.toJSONString(areaalarmOnlineEntity));
        return areaalarmOnlineDao.insertItem(areaalarmOnlineEntity);
    }


    @Override
    public boolean isInArea() {
        //根据坐标[{"uuid":"b9809a0e2dc44a509cc657b4e1a337cc","cardId":131249,"personName":"零件托盘11","posX":1229.117081,"posY":88.575989,"posTime":1694510800318,"isWork":0},{"uuid":"604f9c6baf4047b8ac876b6e64bac39c","cardId":131384,"personName":"BC0148X05","posX":1108.932858,"posY":151.872953,"posTime":1694515624665,"isWork":1},{"uuid":"de03e927fdc34489861dccb976f350a4","cardId":131960,"personName":"BC0097X05","posX":1075.67461,"posY":138.266143,"posTime":1694515627878,"isWork":1},{"uuid":"3bdb92e63a3f4d21bd32df478dc06014","cardId":132097,"personName":"吕志全","posX":1116.8938,"posY":191.845468,"posTime":1694515623043,"isWork":1},{"uuid":"3d87ae429ee148d1a167a0aae67dc212","cardId":132111,"personName":"BC0092D15","posX":1144.660762,"posY":206.727489,"posTime":1694515621822,"isWork":1},{"uuid":"b2a17c0a6a9247eb9714bca5a9b59fd1","cardId":132513,"personName":"货架17","posX":1115.0,"posY":155.0,"posTime":1694506406981,"isWork":0},{"uuid":"8b1b406b48c64f459c3613c640e2009a","cardId":133479,"personName":"BC0096D15","posX":1157.497213,"posY":123.553513,"posTime":1694515630370,"isWork":1}]
        //和区域{"msg":"success","code":0,"page":{"totalCount":2,"pageSize":10,"totalPage":1,"currPage":1,"list":[{"areaNo":10001,"areaId":"10001","areaName":"project1-1","areaPosX1":0.0,"areaPosY1":104.0,"areaPosX2":1350.0,"areaPosY2":230.0},{"areaNo":10002,"areaId":"10002","areaName":"project1-2","areaPosX1":450.0,"areaPosY1":300.0,"areaPosX2":1000.0,"areaPosY2":400.0}]}}
        //判断是否在区域内
        //1.获取区域坐标
        List<AreaEntity> areaEntities = areaDao.selectList(null);
        //[AreaEntity(areaNo=10001, areaId=10001, areaName=project1-1, areaPosX1=0.0, areaPosY1=104.0, areaPosX2=1350.0, areaPosY2=230.0), AreaEntity(areaNo=10002, areaId=10002, areaName=project1-2, areaPosX1=450.0, areaPosY1=300.0, areaPosX2=1000.0, areaPosY2=400.0)]
        log.info("areaEntities:{}", areaEntities);
        //2.根据标签id获取标签坐标
        List<Utype1Entity> utype1Entities = lableonlineinfoDao.listIsWork();
        log.info("utype1Entities:{}", utype1Entities);
        //[Utype1Entity(uuid=b9809a0e2dc44a509cc657b4e1a337cc, cardId=131249, personName=零件托盘11, posX=1229.117081, posY=88.575989, posTime=1694510800318, isWork=0), Utype1Entity(uuid=604f9c6baf4047b8ac876b6e64bac39c, cardId=131384, personName=BC0148X05, posX=1108.932858, posY=151.872953, posTime=1694515624665, isWork=1), Utype1Entity(uuid=de03e927fdc34489861dccb976f350a4, cardId=131960, personName=BC0097X05, posX=1075.67461, posY=138.266143, posTime=1694515627878, isWork=1), Utype1Entity(uuid=3bdb92e63a3f4d21bd32df478dc06014, cardId=132097, personName=吕志全, posX=1116.8938, posY=191.845468, posTime=1694515623043, isWork=1), Utype1Entity(uuid=3d87ae429ee148d1a167a0aae67dc212, cardId=132111, personName=BC0092D15, posX=1144.660762, posY=206.727489, posTime=1694515621822, isWork=1), Utype1Entity(uuid=b2a17c0a6a9247eb9714bca5a9b59fd1, cardId=132513, personName=货架17, posX=1115.0, posY=155.0, posTime=1694506406981, isWork=0), Utype1Entity(uuid=8b1b406b48c64f459c3613c640e2009a, cardId=133479, personName=BC0096D15, posX=1157.497213, posY=123.553513, posTime=1694515630370, isWork=1)]
        //3.判断标签坐标是否在区域坐标内
        for (Utype1Entity tag : utype1Entities) {
            boolean isTagInsideAnyArea = false;
            AreaEntity matchedArea = null;
            for (AreaEntity area : areaEntities) {
                if (isInsideArea(tag.getPosX(), tag.getPosY(), area.getAreaPosX1(), area.getAreaPosY1(), area.getAreaPosX2(), area.getAreaPosY2())) {
                    isTagInsideAnyArea = true;
                    matchedArea = area;
                    break;
                }
            }

            if (isTagInsideAnyArea) {
                // 4. 如果在区域内，判断是否已经报警
                if (hadAlarm(tag)) {
                    // 不再报警
                } else {
                    // 报警，并将报警信息存入数据库
                    saveAlarmToDatabase(tag, matchedArea);
                }
            } else {
                // 5. 如果不在区域内，判断是否已经报警
                if (hadAlarm(tag)) {
                    // 取消报警
                    cancelAlarm(tag);
                } else {
                    // 不报警
                }
            }
        }


        //4.如果在区域内，判断是否已经报警，如果已经报警，不再报警，如果没有报警，报警
        //5.如果不在区域内，判断是否已经报警，如果已经报警，取消报警，如果没有报警，不报警
        //6.如果报警，将报警信息存入数据库
        return false;
    }
    // 判断标签坐标是否在指定区域内
    boolean isInsideArea(double posX, double posY, double areaPosX1, double areaPosY1, double areaPosX2, double areaPosY2) {
        return posX >= areaPosX1 && posX <= areaPosX2 && posY >= areaPosY1 && posY <= areaPosY2;
    }

    // 这是一个伪方法，您需要根据实际情况实现这个方法，判断标签是否已经报警
    boolean hadAlarm(Utype1Entity tag) {
        // 这里是检查标签是否已经报警的逻辑
        return false; // 假设默认没有报警
    }

    // 更新：当报警的时候，将相关信息存入数据库
    void saveAlarmToDatabase(Utype1Entity tag, AreaEntity area) {
        AreaalarmHistoryEntity alarm = new AreaalarmHistoryEntity();

        alarm.setAreaId(area.getAreaId());
        alarm.setLableId(String.valueOf(tag.getCardId()));
        // 假设Areaalarmhistory中有以下字段，如有不同，请修改
        alarm.setLableEmployid(String.valueOf(tag.getCardId())); // 这里假设personId对应的是uuid
        alarm.setEmpname(tag.getPersonName());
        alarm.setAreaname(area.getAreaName());
        alarm.setAlarmTime(new Date()); // 这里假设您希望保存当前时间作为报警时间
        log.info("alarm:{}", alarm);
        log.info("-----------------------");

        // 将报警信息存入数据库的逻辑
        // 假设您有一个对应的DAO方法来插入警报数据
        // areaAlarmHistoryDao.insert(alarm);

        log.info("Tag {} ({}) entered area {}.", tag.getPersonName(), tag.getUuid(), area.getAreaName());
    }

    // 这是一个伪方法，您需要根据实际情况实现这个方法，取消报警
    void cancelAlarm(Utype1Entity tag) {
        // 取消报警的逻辑
        log.info("tag:{}", tag+"离开区域");
    }

    @Override
    public int deleteAllAlarm() {
        return areaalarmOnlineDao.deleteAllAlarm();
    }

    @Override
    public List<AreaalarmOnlineEntity> selectByEmpName(String empName) {
        return areaalarmOnlineDao.selectByEmpName(empName);
    }


}